package com.gateway.core;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.gateway.common.Common;
import com.gateway.dao.ILogicServerDao;
import com.gateway.dao.ILogicServerDaoImpl;
import com.gateway.dao.IUserDao;
import com.gateway.dao.IUserDaoImpl;
import com.gateway.entity.LogicServer;
import com.gateway.entity.User;

/**
 * 网关Handler,主要处理LogicServer的注册/通知，Client登陆验证/服务器信息分发
 * 
 * @author Simple
 * @date 2013-6-28 上午11:25:23
 * @Description TODO
 */
public class GatewayHandler extends IoHandlerAdapter {

  private Logger log=Logger.getLogger(this.getClass());

  private IUserDao userDao=new IUserDaoImpl();

  private ILogicServerDao logicServerDao=new ILogicServerDaoImpl();

  @Override
  public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    super.exceptionCaught(session, cause);
  }

  @Override
  public void messageReceived(IoSession session, Object message) throws Exception {
    log.debug("[Gateway receive message]");
    MyProtocol myProtocol=(MyProtocol)message;
    byte type=myProtocol.getType();
    MyBuffer bodyBuf=new MyBuffer(myProtocol.getBodyData());
    switch(type) {
      case Common.REQ_REGISTER2GATEWAY:
        register2gateway(session, bodyBuf);
        break;
      case Common.REQ_LOGIN_LOGICSERVER:
        loginLogicServer(session, bodyBuf);
        break;
      case Common.REQ_NOTICE:
        notice(bodyBuf);
        break;
      case Common.REQ_USER_REGISTER:
        userRegister(bodyBuf);
        break;
    }
  }

  private void register2gateway(IoSession session, MyBuffer bodyBuf) {
    // 解析
    String logicName=bodyBuf.getString();
    String status=bodyBuf.getString();
    int port=bodyBuf.getInt();
    // 封装
    LogicServer ls=new LogicServer();
    ls.setName(logicName);
    ls.setPort(port);
    ls.setStatus(status);
    ls.setIp(session.getRemoteAddress().toString().replace("/", "").split(":")[0]);
    if(logicServerDao.add(ls) > 0) {
      // 注册到logicServerList
      List<LogicServer> list=Gateway.logicServerList;
      list.add(ls);
      log.debug("register to gateway:" + ls);
      // 展示logicServerList
      log.debug("LogicServerList:");
      for(LogicServer info: list) {
        log.debug(info);
      }
    }
  }

  private void loginLogicServer(IoSession session, MyBuffer bodyBuf) {
    // 解析
    String username=bodyBuf.getString();
    String password=bodyBuf.getString();
    log.debug("Client login:" + username + "|" + password);
    User u=userDao.login(username, password);
    if(null != u) {
      List<LogicServer> ll=Gateway.logicServerList;
      if(ll.size() > 0) {
        LogicServer server=ll.get((int)(Math.random() * ll.size()));
        MyBuffer bodyData=MyBuffer.allocate(100);
        bodyData.putString(server.getName());
        bodyData.putString(server.getIp());
        bodyData.putInt(server.getPort());
        bodyData.flip();
        MyProtocol myProtocol2=new MyProtocol(Common.REQ_EACH, bodyData.getIoBuffer());
        session.write(myProtocol2);
      } else {
        MyBuffer bodyData=MyBuffer.allocate(100);
        bodyData.putString("no LogicServer started");
        bodyData.flip();
        MyProtocol myProtocol2=new MyProtocol(Common.REQ_EACH, bodyData.getIoBuffer());
        session.write(myProtocol2);
      }
    } else {
      log.debug("Accont/password Error!!!");
    }
  }

  private void notice(MyBuffer bodyBuf) {
    String name=bodyBuf.getString();
    String tag=bodyBuf.getString();
    log.debug("From [" + name + "] REQ_NOTICE");
    for(LogicServer server: Gateway.logicServerList) {
      if(server.getName().equals(name)) {
        if("+".equals(tag)) {
          server.setConnections(server.getConnections() + 1);
        } else if("-".equals(tag)) {
          server.setConnections(server.getConnections() - 1);
        }
      }
    }
    for(LogicServer s: Gateway.logicServerList) {
      log.debug(s);
    }
  }

  private void userRegister(MyBuffer bodyBuf) {
    String username2=bodyBuf.getString();
    String password2=bodyBuf.getString();
    String email=bodyBuf.getString();
    User newUser=new User();
    newUser.setEmail(email);
    newUser.setUsername(username2);
    newUser.setPassword(password2);
    if(userDao.add(newUser) > 0) {
      log.debug("register user success");
    } else {
      log.debug("register user faild");
    }
  }

  @Override
  public void messageSent(IoSession session, Object message) throws Exception {
    log.debug("[Gateway send message]");
  }

  @Override
  public void sessionClosed(IoSession session) throws Exception {
    log.debug("[Gateway closed session]");
  }

  @Override
  public void sessionCreated(IoSession session) throws Exception {
    log.debug("[Gateway create session]");
  }

  @Override
  public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    log.debug("[Gateway idle]");
  }

  @Override
  public void sessionOpened(IoSession session) throws Exception {
    log.debug("[Gateway opened session]");
  }
}
